package com.dubbo;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Paths;

public class MyClassLoader extends ClassLoader{
    //private final String CLASS_PATH = "/home/cqh/com/dubbo/";

    private final String CLASS_PATH = "D:\\myyproject\\dubbo-parent\\jvm\\target\\classes\\com\\dubbo\\";

    /**
     * 这里并没有打破双亲委派的一个机制  而是在 findClass方法中加载类  也就是在委派加载都失败之后
     * 使用findClass加载类
     * 会不会产生重复加载的情况
     * @param name
     *         The <a href="#name">binary name</a> of the class
     *
     * @return
     * @throws ClassNotFoundException
     */
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        String file = CLASS_PATH + name;
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            Files.copy(Paths.get(file), byteArrayOutputStream);
            byte[] bytes = byteArrayOutputStream.toByteArray();
            return defineClass(bytes, 0, bytes.length);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

class TestClassLoader {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        System.out.println(ClassLoader.getSystemClassLoader()); //  System.out.println(ClassLoader.getSystemClassLoader());

        MyClassLoader myClassLoader = new MyClassLoader();
        Class class_ = myClassLoader.loadClass("A.class");
        System.out.println(class_.getClassLoader());
        System.out.println(Object.class.getClassLoader());
//        Class class1_ = myClassLoader.loadClass("A.class"); // 直接抛异常不允许重复加载
//        System.out.println(class_ == class1_);

        MyClassLoader myClassLoader1 = new MyClassLoader();
        Class _class = myClassLoader1.loadClass("A.class");
        System.out.println(_class == class_); //false 使用不同的类加载器 即使包名类名相同也会被认为是不同的类

        _class.newInstance();
        //四舍五入
        //System.out.println(Math.round(-11.2));
    }
}



